<?php
class Controller_Online_Zencart extends Controller_Abstract
{
	function actionCategoriesRefresh()
	{
		$this->_view['title'] = '更新网站分类';
		$shop = Shop::find('status=? and platform=?', Q::ini('custom_flag/shop_status/enabled/value') ,'zencart')->order('shop.sort desc')->asArray()->getAll();
		$this->_view['shop'] = $shop;
	}
	
	function actionCategoriesRefreshSave()
	{
		$this->_view['title'] = '更新网站分类（保存）';
		if ($this->_context->isPOST())
		{
			$shop = Shop::find('id=?', $_POST['shop_id'])->asArray()->getOne();
			Helper_BSS_API::getZencartCategories($shop);
		}
		return $this->_redirect(url('Online::Zencart/CategoriesRefresh'));
	}
	
	function actionImport()
	{
		$this->_view['title'] = '导入产品信息';
		$shop = Shop::find('status=1 and platform=?', 'zencart')->order('shop.sort desc')->asArray()->getAll();
		$website_categories = OLM_Zencart_Categories::getZencartCategoriesToSelectFormat($shop);
		$this->_view['website_categories'] = json_encode($website_categories);
	}
	
	function actionImportSave()
	{
		$this->_view['title'] = '导入产品信息（保存）';
		if ($this->_context->isPOST())
		{
			$upload_result = Upload_Files::uploadFile('product', Q::ini('custom_flag/upload_file_type/online/value'));
			if ($upload_result['ack'] == SUCCESS)
			{
				$categories_id = $_POST['website_cat_3'] ? $_POST['website_cat_3'] : ($_POST['website_cat_2'] ? $_POST['website_cat_2'] : $_POST['website_cat_1']);
				$filename = $upload_result['path'];
				$data = Helper_BSS_CSV::csvFileToArray($filename);
				foreach ($data as $d)
				{
					$product_number = str_pad($d['v_products_model'], 6, '0', STR_PAD_LEFT);
					$product_exist = Product_Basic::find('number=?', $product_number)->asArray()->getOne();
					if ($product_exist)
					{
						$zencart_product_info = Online_Zencart_Product::find('product_basic_id=? and shop_id=?', $product_exist['id'], $_POST['website_id'])->getOne();
						if ( ! $zencart_product_info['id'])
						{
							$zencart_product_info = new Online_Zencart_Product();
							$zencart_product_info->product_basic_id = $product_exist['id'];
							$zencart_product_info->shop_id = $_POST['website_id'];
							$zencart_product_info->create_time = CURRENT_DATETIME;
						}
						$zencart_product_info->categories_id = $categories_id;
						$zencart_product_info->storage = $d['v_products_quantity'];
						$zencart_product_info->price = $d['v_products_price'];
						$zencart_product_info->title = $d['v_products_name_1'];
						$zencart_product_info->description = trim($d['v_products_description_1']);
						$zencart_product_info->onsale_flag = $d['v_status'];
						$zencart_product_info->upload_files_id = $upload_result['file_id'];
						$zencart_product_info->last_edit_time = CURRENT_DATETIME;
						$zencart_product_info->save();
					}
				}
				return $this->_redirectMessage('导入成功', '正在返回..', url('Online::Zencart/Import'), $upload_result['ack']);
			}
			else
			{
				return $this->_redirectMessage('导入失败', $upload_result['message'], url('Online::Zencart/Import'), $upload_result['ack']);
			}
		}
	}
	
	function actionList()
	{
		$this->_view['title'] = '产品信息列表';
		$shop = Shop::find('status=1 and platform =?', 'zencart')->order('shop.sort desc')->asArray()->getAll();
		$website_categories = OLM_Zencart_Categories::getZencartCategoriesToSelectFormat($shop);
		$this->_view['website_categories'] = json_encode($website_categories);
		$file = Upload_Files::find('type=?', Q::ini('custom_flag/upload_file_type/online/value'))->order('time desc')->asArray()->getAll();
		$this->_view['file'] = $file;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$this->_view['url_arr'] = json_encode($url_arr);
		$result = Online_Zencart_Product::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$product = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Online::Zencart/List', $url_arr));
			$this->_view['page'] = $page->getPage();
			Helper_BSS_Normal::getProductImgUrl($product);
			$this->_view['product'] = $product;
		}
	}
	
	function actionEdit()
	{
		$this->_view['title'] = '编辑产品信息';
		$id = isset($_GET['id']) ? $_GET['id'] : 0;
		if ($id)
		{
			$product_info = Online_Zencart_Product::find('online_zencart_product.id=?', $id)
				->joinLeft('product_basic', 'number', 'product_basic.id=online_zencart_product.product_basic_id')
				->asArray()->getAll();
			Helper_BSS_Normal::getProductImgUrl($product_info);
			$product_info = $product_info[0];
			$this->_view['product_info'] = $product_info;
			$shop = Shop::find('id=?', $product_info['shop_id'])->asArray()->getAll();
			$website_categories = OLM_Zencart_Categories::getZencartCategoriesToSelectFormat($shop);
			$this->_view['website_categories'] = json_encode($website_categories);
			$default = OLM_Zencart_Categories::getAncestorIdById($product_info['categories_id'], $product_info['shop_id']);
			array_unshift($default, $product_info['shop_id']);
			$this->_view['default'] = json_encode($default);
		}
	}
	
	function actionEditSave()
	{
		$this->_view['title'] = '编辑产品信息（保存）';
		if ($_POST['id'])
		{
			$categories_id = $_POST['website_cat_3'] ? $_POST['website_cat_3'] : ($_POST['website_cat_2'] ? $_POST['website_cat_2'] : $_POST['website_cat_1']);
			$product_info = Online_Zencart_Product::find('id=?', $_POST['id'])->getOne();
			if ($product_info)
			{
				$product_info->categories_id = $categories_id;
				$product_info->description = $_POST['description'];
				$product_info->storage = $_POST['storage'];
				$product_info->price = $_POST['price'];
				$product_info->title = $_POST['title'];
				$product_info->last_edit_time = CURRENT_DATETIME;
				$product_info->save();
				return $this->_redirect(url('Online::Zencart/Edit', array('id' => $_POST['id'])), SUCCESS);
			}
		}
		return $this->_redirectMessage('保存失败', '没有确定产品id', url('Online::Zencart/Edit'), FAILURE);
	}
	
	function actionMultiEditCheck()
	{
		$this->_view['title'] = '按勾选批量修改';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $key => $t)
		{
			$url_arr[$key] = $t;
		}
		if ($_POST['price'] != '' || $_POST['storage'] != '')
		{
			$ids = json_decode($_POST['ids']);
			$sql = 'update online_zencart_product set ';
			if ($_POST['price'] != '' && $_POST['storage'] != '')
			{
				$sql .= ' price=' . $_POST['price'] . ', storage=' . $_POST['storage'];
			}
			if ($_POST['price'] != '' && $_POST['storage'] == '')
			{
				$sql .= ' price=' . $_POST['price'];
			}
			if ($_POST['storage'] != '' && $_POST['price'] == '')
			{
				$sql .= ' storage=' . $_POST['storage'];
			}
			$sql .= ' where id in ('.implode(',', $ids).')';
			QDB::getConn()->execute($sql);
			return $this->_redirectMessage('调整成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
		}
		else
		{
			return $this->_redirectMessage('没有进行任何调整', '正在返回..', url('Online::Zencart/List', $url_arr), FAILURE);
		}
	}
	
	function actionMultiEditSearch()
	{
		$this->_view['title'] = '按搜索批量修改';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $key => $t)
		{
			$url_arr[$key] = $t;
		}
		if ($_POST['price'] || $_POST['storage'])
		{
			$sql = 'update online_zencart_product set ';
			if ($_POST['price'] && $_POST['storage'])
			{
				$sql .= ' price=' . $_POST['price'] . ', storage=' . $_POST['storage'];
			}
			if ($_POST['price'] && empty($_POST['storage']))
			{
				$sql .= ' price=' . $_POST['price'];
			}
			if ($_POST['storage'] && empty($_POST['price']))
			{
				$sql .= ' storage=' . $_POST['storage'];
			}
			QDB::getConn()->execute($sql);
			return $this->_redirectMessage('调整成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
		}
		else
		{
			return $this->_redirectMessage('没有进行任何调整', '正在返回..', url('Online::Zencart/List', $url_arr), FAILURE);
		}
	}
	
	function actionExportCheck()
	{
		$this->_view['title'] = '按勾选导出产品信息';
		$ids = json_decode($_POST['ids']);
		$product_info = Online_Zencart_Product::find('online_zencart_product.id in (?)', $ids)
			->joinLeft('product_basic', 'number, weight, create_time', 'product_basic.id=online_zencart_product.product_basic_id')
			->joinLeft('shop_api_website', 'md5', 'shop_api_website.shop_id=online_zencart_product.shop_id')
			->asArray()->getAll();
		$data = Helper_BSS_CSV::productInfoToCsv($product_info);
		Helper_BSS_CSV::exportCsv($data);
		exit;
	}
	
	function actionExportSearch()
	{
		$this->_view['title'] = '按搜索导出产品信息';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $key => $t)
		{
			$url_arr[$key] = $t;
		}
		$where = Online_Zencart_Product::buildSearchWhere($url_arr);
		$product_info = Online_Zencart_Product::find($where)
			->joinLeft('product_basic', 'name, number, weight, create_time', 'product_basic.id=online_zencart_product.product_basic_id')
			->joinLeft('shop_api_website', 'md5', 'shop_api_website.shop_id=online_zencart_product.shop_id')
			->asArray()->getAll();
		$data = Helper_BSS_CSV::productInfoToCsv($product_info);
		Helper_BSS_CSV::exportCsv($data);
		exit;
	}
	
	function actionOnSaleCheck()
	{
		$this->_view['title'] = '按勾选改变上下架状态';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $k => $t)
		{
			$url_arr[$k] = $t;
		}
		$ids = json_decode($_POST['ids']);
		$onsale_flag = intval($_POST['onsale_val']);
		foreach ($ids as $id)
		{
			QDB::getConn()->execute('update online_zencart_product set onsale_flag=' . $onsale_flag . ' where id=' . $id);
		}
		return $this->_redirectMessage('调整成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
	}
	
	function actionOnSaleSearch()
	{
		$this->_view['title'] = '按搜索改变上下架状态';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $k => $t)
		{
			$url_arr[$k] = $t;
		}
		$onsale_flag = intval($_POST['onsale_val']);
		$where = Online_Zencart_Product::buildSearchWhere($url_arr);
		$product_info = Online_Zencart_Product::find($where)
			->joinLeft('product_basic', '', 'product_basic.id=online_zencart_product.product_basic_id')
			->joinLeft('shop_api_website', '', 'shop_api_website.shop_id=online_zencart_product.shop_id')
			->asArray()->getAll();
		foreach ($product_info as $pi)
		{
			QDB::getConn()->execute('update online_zencart_product set onsale_flag=' . $onsale_flag . ' where id=' . $pi['id']);
		}
		return $this->_redirectMessage('调整成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
	}
	
	function actionMoveCategoriesCheck()
	{
		$this->_view['title'] = '按勾选分类移动';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $k => $t)
		{
			$url_arr[$k] = $t;
		}
		$ids = json_decode($_POST['ids']);
		$shop_id = $_POST['move_website_id'];
		$categories_id = $_POST['move_website_cat_3'] ? $_POST['move_website_cat_3'] : ($_POST['move_website_cat_2'] ? $_POST['move_website_cat_2'] : $_POST['move_website_cat_1']);
		if ($shop_id && $categories_id)
		{
			$product_info = Online_Zencart_Product::find('id in (?)', $ids)->asArray()->getAll();
			foreach ($product_info as $pi)
			{
				Online_Zencart_Product::moveCategories($pi, $shop_id, $categories_id);
			}
			return $this->_redirectMessage('移动成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
		}
		return $this->_redirectMessage('移动失败', '没有选择网站和分类', url('Online::Zencart/List', $url_arr), FAILURE);
	}
	
	function actionMoveCategoriesSearch()
	{
		$this->_view['title'] = '按搜索分类移动';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $k => $t)
		{
			$url_arr[$k] = $t;
		}
		$shop_id = $_POST['move_website_id'];
		$categories_id = $_POST['move_website_cat_3'] ? $_POST['move_website_cat_3'] : ($_POST['move_website_cat_2'] ? $_POST['move_website_cat_2'] : $_POST['move_website_cat_1']);
		if ($shop_id && $categories_id)
		{
			$where = Online_Zencart_Product::buildSearchWhere($url_arr);
			$product_info = Online_Zencart_Product::find($where)
				->joinLeft('product_basic', '', 'product_basic.id=online_zencart_product.product_basic_id')
				->joinLeft('shop_api_website', '', 'shop_api_website.shop_id=online_zencart_product.shop_id')
				->asArray()->getAll();
			foreach ($product_info as $pi)
			{
				Online_Zencart_Product::moveCategories($pi, $shop_id, $categories_id);
			}
			return $this->_redirectMessage('移动成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
		}
		return $this->_redirectMessage('移动失败', '没有选择网站和分类', url('Online::Zencart/List', $url_arr), FAILURE);
	}
	
	function actionPushCheck()
	{
		$this->_view['title'] = '按勾选推送产品';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $k => $t)
		{
			$url_arr[$k] = $t;
		}
		$ids = json_decode($_POST['ids']);
		$product_info = Online_Zencart_Product::find('online_zencart_product.id in (?)', $ids)
			->joinLeft('product_basic', 'number, weight, create_time', 'online_zencart_product.product_basic_id=product_basic.id')
			->joinLeft('shop_api_website', 'md5', 'online_zencart_product.shop_id=shop_api_website.shop_id')
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getAll();
		$wn = $product_info[0]['md5'];
		$api_type = md5($product_info[0]['platform']);
		$data = Helper_BSS_CSV::pushProductInfoToCsv($product_info);
		Helper_BSS_API::pushZencartProductInfo($data, $wn, $api_type, CURRENT_USER_NAME);
		return $this->_redirectMessage('推送成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
	}
	
	function actionPushSearch()
	{
		$this->_view['title'] = '按搜索推送产品';
		$temp = json_decode($_POST['url_arr']);
		$url_arr = array();
		foreach ($temp as $k => $t)
		{
			$url[$k] = $t;
		}
		$where = Online_Zencart_Product::buildSearchWhere($url_arr);
		$product_info = Online_Zencart_Product::find($where)
			->joinLeft('product_basic', 'name, number, weight, create_time', 'online_zencart_product.product_basic_id=product_basic.id')
			->joinLeft('shop_api_website', 'md5', 'shop_api_website.shop_id=online_zencart_product.shop_id')
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getAll();
		$wn = $product_info[0]['md5'];
		$api_type = md5($product_info[0]['platform']);
		$data = Helper_BSS_CSV::pushProductInfoToCsv($product_info);
		Helper_BSS_API::pushZencartProductInfo($data, $wn, $api_type, CURRENT_USER_NAME);
		return $this->_redirectMessage('推送成功', '正在返回..', url('Online::Zencart/List', $url_arr), SUCCESS);
	}
}